/*
 * @lc app=leetcode.cn id=21 lang=javascript
 *
 * [21] 合并两个有序链表
 *
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
 *
 * algorithms
 * Easy (52.27%)
 * Total Accepted:    45.8K
 * Total Submissions: 87K
 * Testcase Example:  '[1,2,4]\n[1,3,4]'
 *
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 *
 * 示例：
 *
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 *
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

function ListNode(val) {
  this.val = val
  this.next = null
}

function numToList(num) {
  let splited = num
  if (!Array.isArray(num)) {
    splited = num
      .toString()
      .split('')
      .reverse()
  }
  const originNode = new ListNode(splited.shift(0))
  splited.reduce((node, n) => {
    node.next = new ListNode(n)
    return node.next
  }, originNode)
  return originNode
}

function listToArray(li) {
  const r = [li.val]
  while (li.next) {
    r.push(li.next.val)
    li = li.next
  }
  return r
}

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
  if (!l1) return l2
  if (!l2) return l1
  let first = undefined
  let tmp = undefined
  let l1tmp = l1
  let l2tmp = l2
  if (l1tmp.val > l2tmp.val) {
    first = tmp = new ListNode(l2tmp.val)
    l2tmp = l2tmp.next || {}
  } else {
    first = tmp = new ListNode(l1tmp.val)
    l1tmp = l1tmp.next || {}
  }
  while (l1tmp.val !== undefined || l2tmp.val !== undefined) {
    if (l1tmp.val === undefined) {
      tmp.next = new ListNode(l2tmp.val)
      tmp = tmp.next
      l2tmp = l2tmp.next || {}
    } else if (l2tmp.val === undefined) {
      tmp.next = new ListNode(l1tmp.val)
      tmp = tmp.next
      l1tmp = l1tmp.next || {}
    } else if (l1tmp.val > l2tmp.val) {
      tmp.next = new ListNode(l2tmp.val)
      tmp = tmp.next
      l2tmp = l2tmp.next || {}
    } else {
      tmp.next = new ListNode(l1tmp.val)
      tmp = tmp.next
      l1tmp = l1tmp.next || {}
    }
  }
  return first
}

// console.log(
//   listToArray(
//     mergeTwoLists(
//       numToList([-8, -6, -6, -3, 0, 4, 4, 8]),
//       numToList([-7, -4, -3, 0, 5]),
//     ),
//   ),
// )
